package com.trs.publish.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.trs.publish.domain.Power;
import com.trs.publish.domain.PowerCatalog;
import com.trs.publish.domain.SearchParam;
import com.trs.publish.service.PowerCatalogService;
import com.trs.publish.service.PowerService;
import com.trs.publish.service.RolePowerService;



/**
 * 权限管理
 * @author jia.haihong
 *
 */

@Controller
public class PowerController{ 
	
	private static final Logger logger = LoggerFactory.getLogger(PowerController.class);

	@Autowired 
	private PowerService powerService;
	
	@Autowired 
	private PowerCatalogService powerCatalogService;
	
	@Autowired 
	private RolePowerService rolePowerService;
	
	@RequestMapping(value = "/toPower")
    public ModelAndView toUser(ModelAndView mav) {
        mav.setViewName("power/list");
        return mav;
    }  
	
	@RequestMapping(value = "/power", method = RequestMethod.PATCH)
    @ResponseBody
    public Object search(@RequestBody SearchParam searchParam) {
		String powername = searchParam.getPowername();
		String memo = searchParam.getMemo();
		String startTime = searchParam.getStartTime();
		String endTime = searchParam.getEndTime();
		
		//根据查询条件获取权限列表
		Power power = new Power();
		power.setPowername(powername);
		power.setMemo(memo);
		power.setStartTime(startTime);
		power.setEndTime(endTime);
		
		//mybatis分页
		PageHelper.startPage(searchParam);
		List<Power> list = powerService.getList(power);
		//获取资源分类的Map
		Map<Long,String> powerCatalogMap = this.getPowerCatalogMap();
		//转换结果集中的catalog
		for(Power p:list){
			p.setCatalogStr1(powerCatalogMap.get(p.getCatalog1()));
			p.setCatalogStr2(powerCatalogMap.get(p.getCatalog2()));
		}
		PageInfo<Power> pageInfo = new PageInfo<Power>(list);
        return pageInfo;
    }
	
	//获取所有的资源分类，并转换为map
	private Map getPowerCatalogMap() {
		Map<Long,String> map = new HashMap<Long,String>();
		PowerCatalog powerCatalog = new PowerCatalog();
		List<PowerCatalog> list = powerCatalogService.getList(powerCatalog);
		for(PowerCatalog pc:list){
			map.put(pc.getId(),pc.getCatalogname());
		}
		return map;
	}

	/**
	 * 删除
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/power/{id}", method = RequestMethod.DELETE)
	@ResponseBody
	public Object delete(@PathVariable("id") long id) {
		Map<String, Object> map = new HashMap<String, Object>();
		logger.debug("删除权限id=" + id);
		//删除关系表
		rolePowerService.deleteByPowerId(id);
		//删除权限
		powerService.deletePower(id);
		map.put("message", "删除成功！");
		return map;
	}
	
	/**
	 * 获取指定对象
	 * 
	 * @param userId
	 * @return
	 */
	@RequestMapping(value = "/power/{id}", method = RequestMethod.GET)
	public ModelAndView get(ModelAndView mav,@PathVariable("id") long id) {
		logger.debug("查询单个权限id=" + id);
		Power power = new Power();
		//获取用户信息
		if(id==0){
			power.setId(id);
		}else{
			power = powerService.findById(id);
		}
		
		//一级分类列表
		List<PowerCatalog> topPowerCatalogs = powerCatalogService.queryByPid(0);
		mav.addObject("topPowerCatalogs", topPowerCatalogs);
		
		//TODO 二级分类根据一级分类ajax加载
		//二级分类列表
		PowerCatalog pc = new PowerCatalog();
		List<PowerCatalog> secondPowerCatalogs = powerCatalogService.getList(pc);
		mav.addObject("secondPowerCatalogs", secondPowerCatalogs);
		
		//获取角色信息
		mav.addObject("power", power);
		mav.setViewName("power/detail");
		return mav;
	}
	
	/**
	 * 更新/新增
	 * 
	 * @param user
	 * @return
	 */
	@RequestMapping(value = "/power", method = RequestMethod.PUT)
	@ResponseBody
	public Object addOrUpdate(@RequestBody Power power) {
		Map<String, Object> map = new HashMap<String, Object>();
		StringBuffer message = new StringBuffer();
		
		long id = power.getId();
		//判断权限编码
		if(StringUtils.isEmpty(power.getPowername())){
			message.append("权限编码不能为空。");
		}
		//判断权限描述
		if(StringUtils.isEmpty(power.getMemo())){
			message.append("权限描述不能为空。");
		}
		
		//判断权限编码是否已经存在
		/*List<Power> tempList = powerService.getList(power);
		if (tempList!=null&&tempList.size()>0) {
			message.append("该权限编码已存在。");
		}*/
		
		if(StringUtils.isEmpty(message)){
			if(id == 0){//新增方法
				//重置id
				power.setId(null);
				powerService.save(power);
			}else{//修改方法
				powerService.update(power);
			}
		}
		map.put("message", message.toString());
		return map;
	}
}

